package com.lw.netty.server;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.scheduling.annotation.Async;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class DiscardServer {
	EventLoopGroup bossGroup = null; // (1)
	EventLoopGroup workerGroup = null;
	private Channel channel;
	public DiscardServer() {
		System.out.println("DiscardServer construct");
	}

	public void run(int port) throws Exception {
		bossGroup = new NioEventLoopGroup(); // (1)
		workerGroup = new NioEventLoopGroup();
		ServerBootstrap b = new ServerBootstrap(); // (2)
		b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new MyChannelInitializer())
				.option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
		ChannelFuture f = b.bind(port).sync(); // (7)
		channel =	f.channel();
		System.out.println(1/0);

	}
	@PostConstruct
	@Async
	public void start() throws Exception {
		System.err.println("初始化开始。。。");
		run(8999);
	}
	

	@PreDestroy
	public void stop() {
		System.err.println("资源释放。。。");
		workerGroup.shutdownGracefully();
		bossGroup.shutdownGracefully();
		try {
			channel.closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
